﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace LPNRTool
{
    class udpc
    {
        WriteLog trace = new WriteLog();

        private UdpClient myUdpClient=null;


        public int localPort = 10040;

        byte[] senddata;
 
        //启动消息发送
        public void StartUdpSend(byte[] buf)
        {
            senddata=new byte[buf.Length];
            Array.Copy(buf, senddata, buf.Length);
          
            Thread SendMsgThread = new Thread(SendMsg);
            SendMsgThread.IsBackground = true;
            SendMsgThread.Start();
        }
        //发送消息线程
        private void SendMsg()
        {
            trace.WriteLogFile("udp发送线程开启");
            if (myUdpClient != null)
            {
                IPEndPoint remote = new IPEndPoint(IPAddress.Parse("192.168.10.118"), 10041);
                myUdpClient.Send(senddata, senddata.Length, remote);
            }
            else {
                trace.WriteLogFile("未将udpclient 实例化");
            }
        }

        public void StartUdpReceive()
        {
            //showMsg = new ShowMsg(showmsg);

            IPEndPoint localPoint = new IPEndPoint(IPAddress.Any, 0);
            myUdpClient = new UdpClient();

            Thread ReceMsgThread = new Thread(ReceiveMsg);
            ReceMsgThread.IsBackground = true;
            ReceMsgThread.Start();
        }
        //显示消息的被委托的方法
        private void showmsg(string text)
        {
            trace.WriteLogFile(text);
        }
        /// <summary>
        ///消息接收线程
        /// </summary>
        private void ReceiveMsg()
        {
            trace.WriteLogFile("udp接受线程开启");
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try 
                { 
                    byte[] getdata ;
                    getdata = myUdpClient.Receive(ref iPEndPoint);//任何ip发送过来的都接受
                    string msg = Common.byteToHexStr(getdata);
                    trace.WriteLogFile(msg);
                }
                catch(ThreadAbortException)
                {
                    
                }
                catch(Exception ex)
                {
                    trace.WriteLogFile("异常" + ex.Message.ToString());
                }
            }
        }
    }
}
